from flask_shop.menu import menu_api
from flask_shop import models
from flask import request
from flask_restful import Resource


class MenuView(Resource):
    def get(self):
        menu_list = []
        type = request.args.get('type')
        if type == 'list':
            # 获取数据，并将数据填充到menu_list
            mu = models.Menu.query.filter(models.Menu.level != 0).all()
            for m in mu:
                menu_list.append(m.to_dict())
        else:
            # 获取数据，并将数据填充到menu_list
            mu = models.Menu.query.filter(models.Menu.level == 1).all()
            for m in mu:
                # 获取一级菜单转换为json
                first_menu = m.to_dict()
                # 给2级菜单创建保存容器
                first_menu['children'] = []
                for sm in m.children:
                    # 获取2级菜单转为json
                    second_menu = sm.to_dict()
                    first_menu['children'].append(second_menu)
                menu_list.append(first_menu)
        return menu_list


menu_api.add_resource(MenuView, '/menu')
